<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;
class Login extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->assign("think_var",cookie('think_var'));

    }

    public function lang()
    {
        switch($_GET["lang"])
        {
            case 'cn' :
                cookie('think_var','zh-cn');
                break;
            case 'en':
                cookie('think_var','en-us');
                break;
        }
    }
    //登陆
    public function login()
    {
        if (input("post.")) {
            $data = input("post.");

                $userInfo = Db::name("users")->where(['user_name' => $data['username']])->find();
                $data = Db::name("users")
                    ->where([
                        'user_name'=>$data['username'],
                        'user_pwd'=>md5($data['password'].$userInfo['regcode']),
                        'status' => 0
                    ])->find();
                Session::set('uid', $userInfo['user_id']);
                Session::set('user_name', $userInfo['user_name']);
                if (!empty($data)) {
                     //大于 6 小时未投资  则 冻结账号
                    if(time()-$data["create_time"]>43200&&$data["level"]==1)
                    {
                        $res=Db::name("users")->update(["status"=>1,"user_id"=>$data["user_id"]]);
                        if($res)
                        {
                            return AjaxReturn(1,lang("error_status"));
                        }else
                        {
                            return AjaxReturn(1,lang("error_status"));
                        }
                    }
                    //投资金额 不同于 且有本金提现记录
                    $balanceData=Db::name("balance")->where("user_id",$data["user_id"])->find();
                    $withDraw=Db::name("withdraw")->where(["balance_type"=>0,"status"=>1,"user_id"=>$data["user_id"]])->order("id desc")->find();
                    if(!empty($withDraw))
                    {
                        if($balanceData["balance"]<$withDraw["money"]&&time()-$withDraw["update_time"]>21600)
                        {
                            $res=Db::name("users")->update(["status"=>1,"user_id"=>$data["user_id"]]);
                            $res2=changeRecom($data["user_id"],$num=-1);
                            if($res&&$res2)
                            {
                                return AjaxReturn(1,lang("error_status"));
                            }else
                            {
                                return AjaxReturn(1,lang("error_status"));
                            }
                        }
                    }
                    if($data["status"]==1)
                    {
                        return AjaxReturn(1,lang("error_status"));
                    }else
                    {
                        return AjaxReturn(0,lang("success_login"));
                    }
                } else {
                  return AjaxReturn(1,lang("error_login"));
                }

        } else {
            return $this->fetch();
        }
    }
    //忘记密码
    public function forget()
    {
        $user_id = 0;
        if(input("post.")){
            $data = input("post.");
            $users = Db::name('users')->where('user_name',$data['username'])->find();
            $user_id = $users['user_id'];
            if($users == "")
            {
                $data['status'] = 0;
                $data['msg'] = lang('forget_user_false');
                return $data;
            }
            $encrypt_answer = Db::name('encrypt_answer')->where(['encrypt'=>$data['question'],'answer'=>$data['chose_question']])->find();
            if($encrypt_answer == ""){
                $data ['status'] = 0;
                $data ['msg'] = lang('forget_answer_false');
                return $data;
            }else{
                $data['status'] = 1;
                $data['user_id'] = $users['user_id'];
                return $data;
            }
        }else{
// 获取密码问题
            $encrypt = Db::name('encrypt')->select();
            $this->assign('encrypt',$encrypt);
            $this->assign('user_id',$user_id);
            return $this->fetch();
        }
    }

    // 修改密码页面
    public function forget1()
    {
        if(input('post.')){
            $data = input('post.');
            if($data['password'] != $data['newpassword']){
                $data['status'] = 0;
                $data['msg'] = lang('pwd_pass_falses');
                return $data;
            }
// 修改密码
            $result = Db::name('users')->where('user_id',$data['user_id'])->update(['user_pwd'=>md5($data['password'])]);
            if($result){
                $data['status'] = 1;
                $data['msg'] = lang('set_success_edit');
                return $data;
            }else{
                $data['status'] = 0;
                $data['msg'] = lang('set_error_edit');
                return $data;
            }

        }else{
// $request = input('params');
            $this->assign('user_id',input('user_id'));
            return $this->fetch();
        }
    }
    //注册
    public function register()
    {
        if (input("post.")) {
            $request = Request::instance();
            $ip = $request->ip();
            $data = input("post.");
            //上级ID
            $pid = Db::name("member")
                ->field("id,referee_num")
                ->where([
                    'regcode' => $data['regcode'],
                ])->find();
            $num = $pid['referee_num']+1;
            $number = Db::name("member")
                ->where(['regcode' => $data['regcode']])
                ->update(['referee_num' => $num]);
            //家族路径
            $path = Db::name("member")
                ->field("path")
                ->where([
                    'regcode' => $data['regcode'],
                ])->find();
            //短信验证码
            $sms = Db::name("sms")
                ->where([
                    'sms' => $data['sms'],
                    'ip'  => $ip,
                    'phone'=> $data['mobile']
                ])
                ->find();
            //已注册用户查询
            $mobile = Db::name('member')
                ->where([
                    'mobile'=> $data['mobile']
                ])
                ->find();
            $time = date('Y-m-d H:i:s');
            //邀请码
            $regcode = $this->makePassword();
            if($data['sms'] == $sms['sms'] && $ip == $sms['ip'] && $data['mobile'] == $sms['phone'] && $time <= $sms['end_time'] && $mobile == ''){
                $data = [
                    'username' => $data['mobile'],
                    'mobile' => $data['mobile'],
                    'password' => md5($data['password'].$regcode),
                    'truename' => $data['truename'],
                    'id_card' => $data['id_card'],
                    'pay_password' => md5($data['pay_password']),
                    'pid' => $pid['id'],
                    'path'=> $path['path'] . $pid['id'] . ',',
                    'register_time' => date("Y-m-d H:i:s"),
                    'regcode' => $regcode,
                ];
                $id = Db::name("member")
                    ->insert($data);
                return $id;
            }else{
                return 0;
            }
        } else {
            return $this->fetch();
        }
    }
    //生成邀请码
    public function makePassword($length = 16)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        // 在 $chars 中随机取 $length 个数组元素键名
        $keys = array_rand($chars, $length);
        $password = '';
        for ($i = 0; $i < $length; $i++) {
            // 将 $length 个数组元素连接成字符串
            $password .= $chars[$keys[$i]];
        }
        return $password;
    }
    //发送短信
    public function SendSms()
    {
        header("Content-Type:text/html;charset=utf-8");
        $ch = curl_init();
        $apikey = "47ac590d538b4401fb60b3e460b0db0c";//修改为您的apikey(ey(https://www.yunpian.com)登录官)登录官网后获取
        $mobile = $_POST['tel'];
		$code =  rand(1000,9999);
        // 发送模板短信
        // 需要对value进行编码
        $data = array('tpl_id' => '2460064', 'tpl_value' => ('#code#'). '='.urlencode($code), 'apikey' => $apikey, 'mobile' => $mobile);
        //print_r ($data);
        $json_data = $this->tpl_send($ch,$data);
        $array = json_decode($json_data,true);
        if($array == 1){
            $request = Request::instance();
            $ip = $request->ip();
            $mm=60*5;
            $start_time = date('Y-m-d H:i:s');
            $end_time = date("Y-m-d H:i:s",strtotime($start_time)+$mm);
            $sql = Db::name("sms")
                ->insert([
                    'sms' => $code,
                    'static_time' => $start_time,
                    'end_time' => $end_time,
                    'ip' => $ip,
                    'phone' => $mobile
                ]);
            $data ['status'] = 1;
            $data ['msg'] = "发送成功！";
        }else{
            $data ['status'] = 0;
            $data ['msg'] = "发送失败！";
        }
        return $data;
    }
    function tpl_send($ch,$data){
        curl_setopt ($ch, CURLOPT_URL,
            'https://sms.yunpian.com/v2/sms/tpl_single_send.json');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        $error = curl_error($ch);
        $this->checkErr($result,$error);
        return $result;
    }
    function checkErr($result,$error) {
        if($result === false)
        {
            echo 'Curl error: ' . $error;
        }
        else
        {
            //echo '操作完成没有任何错误';
        }
    }
    //验证身份证是否合法
    function isCreditNo(){
        $vStr = input("post.id_card");
        $vCity = array(
            '11','12','13','14','15','21','22',
            '23','31','32','33','34','35','36',
            '37','41','42','43','44','45','46',
            '50','51','52','53','54','61','62',
            '63','64','65','71','81','82','91'
        );
        if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
        if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
        $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
        $vLength = strlen($vStr);
        if ($vLength == 18) {
            $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
        } else {
            $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
        }
        if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
        if ($vLength == 18) {
            $vSum = 0;
            for ($i = 17 ; $i >= 0 ; $i--) {
                $vSubStr = substr($vStr, 17 - $i, 1);
                $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
            }
            if($vSum % 11 != 1) return false;
        }
        return true;
    }
    //退出登录
    public function quit()
    {
        Session::set('id', null);
        Session::set('username', null);
        return $this->fetch('login/login');
    }
}
